var App = App || {};

App.getParams = function() {
	var paramStr = location.href.split('?')[1];

	if (paramStr == null) {
		return {};
	}

	if (paramStr == '') {
		return {};
	}

	var params = {};

	var arr = paramStr.split('&');
	for (var i = 0; i < arr.length; i++) {
		var ar = arr[i].split('=');

		params[ar[0]] = decodeURIComponent(ar[1]);
	}

	return params;
};

App.getAnchorParams = function() {
	var paramStr = location.href.split('#')[1];

	if (paramStr == null) {
		return {};
	}

	if (paramStr == '') {
		return {};
	}

	var params = {};

	if (paramStr.indexOf('?') != -1) {
		paramStr = paramStr.split('?')[1];
	}

	var arr = paramStr.split('&');
	for (var i = 0; i < arr.length; i++) {
		var ar = arr[i].split('=');

		params[ar[0]] = decodeURIComponent(ar[1]);
	}

	return params;
};

App.goUrl = function(url, params, method, newWin){

	if (!url) {
		return;
	}

	var form = document.createElement("form");

	form.action = url;

	if (newWin) {
		form.target = '_blank';
	} else {
		form.target = '_top';
	}

	form.method = method ? method : 'post';

	for (var key in params) {
		var input = document.createElement('input');
		input.name = key;
		input.value = params[key];

		form.appendChild(input);
	}

	document.body.appendChild(form);

	form.submit();

	form.parentNode.removeChild(form);
};

App.getFieldValues = function(formEl) {
	var o = {};
	formEl.find('input,select,textarea').each(function() {
		var el = $(this);

		if (!el.is('[name]')) return;

		o[el.attr('name')] = el.val();
	});

	return o;
};

App.goError = function(msg, params) {
	var urlParams = '';
	for (var key in params) {
		if(key == 'uid'){
			urlParams = urlParams + '&' + key + '=' + (params[key] ? encodeURIComponent(params[key]) : '');
		}
	}
	window.location.href = base + 'vm/error?msg=' + (msg ? encodeURIComponent(msg) : '') + urlParams;
};

App.ajax = function(url, method, params, callback) {
	$.ajax({
		url : url,
		type : method,
		data : params,
		success : function(d, status, xhr) {
			if (!(d instanceof Object)) {
				try {d = $.parseJSON(d)}catch (e) {}
			}

			callback ? callback(d) : null;
		}

	});
};

App.getFrom = function(url, callback) {
	App.ajax(url, 'get', null, callback);
};

App.postTo = function(url, params, callback) {
	App.ajax(url, 'post', params, callback);
};

